import { atomWithStorage } from 'jotai/utils'
import { atom } from 'jotai'
import { Chat, storageKeys } from '@/types'

const chatIdStorage = atomWithStorage<string | null>(storageKeys.ChatIId, null)
export const chatsAtom = atomWithStorage<Chat[]>(storageKeys.Chats, [])

export const currentChatIdAtom = atom(
  (get) => {
    const storedId = get(chatIdStorage)
    const chats = get(chatsAtom)
    if (storedId && chats.some(chat => chat.id === storedId)) {
      return storedId
    }
    return chats.length > 0 ? chats[0].id : null
  },
  (_, set, update: string) => {
    set(chatIdStorage, update)
  },
)

export const currentChatAtom = atom(
  (get) => {
    const id = get(currentChatIdAtom)
    const chats = get(chatsAtom)
    const current = chats.find(chat => chat.id === id)
    return current ? current : null
  },
)
